package com.baosight.risk.web.workflow;

import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.service.soa.XLocalManager;
import com.baosight.risk.api.system.ISysRoleService;
import com.baosight.risk.api.workflow.WorkflowAuthService;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.constant.WorkflowConstant;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.IDGenerator;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.workflow.WorkFlowManager;
import com.baosight.risk.service.fltd.impl.FltdProcessServiceImpl;
import com.baosight.risk.service.system.entity.SysRole;
import com.baosight.risk.service.workflow.entity.WorkflowAuth;
import com.baosight.risk.service.workflow.vo.WorkflowAuthVO;
import com.baosight.risk.service.workflow.vo.WorkflowCompleteVO;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者： lishaoqing
 * 时间： 2019年06月17日
 * 描述： WorkflowAuthController
 * 版本: v1.0
 */
@Api(value = "工作流测试类", description = "工作流测试类", produces = MediaType.APPLICATION_JSON)
@Slf4j
@RestController
@RequestMapping("/workflow/auth")
public class WorkflowAuthController extends BaseController {

    @Autowired
    private WorkflowAuthService workflowAuthService;

    @Autowired
    private WorkFlowManager workFlowManager;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IXtzyCompanyService companyService;

    /**
     * 分页查询数据,模糊查询
     *
     * @param filed 查询条件
     * @return 流程定义列表
     */
    @GetMapping("list")
    public AjaxResult list(@RequestParam(value = "processName", required = false) String filed) {
        startPage();
        return getResultPage(workflowAuthService.queryAll(filed));
    }

    @ApiOperation("根据流程定义编码查询人工活动节点")
    @GetMapping("nodes")
    public AjaxResult nodes(WorkflowAuthVO workflowAuth) {
        List<WorkflowAuthVO> nodes = workflowAuthService.selectNodes(workflowAuth.getProcessKey());
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("total", nodes.size());
        ajaxResult.put("data", nodes);
        return ajaxResult;
    }

    @ApiOperation("查询所有角色")
    @GetMapping("selectRoles")
    public AjaxResult selectRoles() {
        SysRole sysRole = new SysRole();
        sysRole.setStatus("10");
        List<SysRole> roles = roleService.selectRole(sysRole);
        List<Map<String, Object>> list = new ArrayList<>();

        for (SysRole role : roles) {
            Map<String, Object> map = new HashMap<>();
            map.put("value", role.getId());
            map.put("label", role.getRoleName());
            map.put("children", new HashMap<String, Object>());
            list.add(map);
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("total", list.size());
        ajaxResult.put("data", list);
        return ajaxResult;
    }

    @ApiOperation("新增流程授权规则")
    @PostMapping("save")
    public AjaxResult save(@RequestBody List<WorkflowAuthVO> auths) {
        AjaxResult result = AjaxResult.success();
        try {
            for (WorkflowAuthVO auth : auths) {
                WorkflowAuth workflowAuth = new WorkflowAuth();
                BeanUtils.copyBeanProp(workflowAuth, auth);
                workflowAuth.setId(IDGenerator.getIdStr());
                workflowAuthService.insert(workflowAuth);
            }
        } catch (Exception e) {
            result = AjaxResult.error();
            throw e;
        }
        return result;
    }

    @ApiOperation("获取下一步审核人")
    @GetMapping("getNextUsers")
    public AjaxResult getUsers(String id) {
        XtzyUser sysUser = ShiroUtils.getUser();
        List<XtzyUser> nextUsers = workFlowManager.findNextUsers(sysUser, id);

        WorkflowCompleteVO completeVO = new WorkflowCompleteVO();
        completeVO.setUsers(nextUsers);
        if (nextUsers == null) {
            completeVO.setIsEnd("1");
        } else {
            completeVO.setIsEnd("0");
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("data", completeVO);
        return ajaxResult;
    }

    @ApiOperation("批量审核")
    @PostMapping("submit")
    public AjaxResult batchSubmit(@RequestBody WorkflowCompleteVO vo) {
        if ("1".equals(vo.getApprovalResult())) {
            workFlowManager.batchSubmit(vo.getComment(), vo.getBusinessKeys(), vo.getUsers());
        } else {
            workFlowManager.batchReturns(vo.getComment(), vo.getBusinessKeys());
        }
        return AjaxResult.success();
    }

    @ApiOperation("启动一个流程（测试方法）")
    @PostMapping("startProcess")
    public AjaxResult startProcess(@RequestBody WorkflowAuthVO vo) {
//        workFlowManager.startProcess(vo.getProcessKey(), vo.getBusinessKey(), vo.getVariables());

        XtzyUser sysUser = ShiroUtils.getUser();
        String starterId = sysUser.getUserCode();
        EiInfo inInfo = new EiInfo();
        //启动流程实例
        inInfo.set("processDefinitionKey", vo.getProcessKey()); //流程定义编码
        inInfo.set("starterId", starterId); //流程启动者ID
        inInfo.set("businessKey", vo.getBusinessKey());
        inInfo.set("variables", vo.getVariables());
//        List<Map<String,String>> nextActivityUserList = new ArrayList<>();
//        Map<String,String> nextAuditUser = new HashMap<>();
//        nextAuditUser.put("userId","lishaoqing");
//        nextAuditUser.put("userName","李少清");
//        nextActivityUserList.add(nextAuditUser);
//        nextAuditUser = new HashMap<>();
//        nextAuditUser.put("userId","test");
//        nextAuditUser.put("userName","test员工");
//        nextActivityUserList.add(nextAuditUser);
//
//        inInfo.set("nextActivityUserList",nextActivityUserList);
        inInfo.set(EiConstant.serviceName, "EW11");
        inInfo.set(EiConstant.methodName, "startProcess");
        EiInfo outInfo = XLocalManager.call(inInfo);
        String processInstanceId = outInfo.getString("processInstanceId");
        return AjaxResult.success("操作成功", processInstanceId);
    }

    @ApiOperation("提交流程（测试方法）")
    @PostMapping("testSubmit")
    public AjaxResult testSubmit(String processInstanceId) {
        XtzyUser sysUser = ShiroUtils.getUser();

        List<Map<String, String>> nextActivityUserList = new ArrayList<>();
        Map<String, String> nextAuditUser = new HashMap<>();
        nextAuditUser.put("userId", "lishaoqing");
        nextAuditUser.put("userName", "李少清");

//        nextAuditUser.put("userId","cuishihao");
//        nextAuditUser.put("userName","Chris Cui");

//        nextAuditUser.put("userId","yanbo");
//        nextAuditUser.put("userName","波哥");
        nextActivityUserList.add(nextAuditUser);

        FltdProcessServiceImpl processService = new FltdProcessServiceImpl();
        String taskId = processService.getTaskId(sysUser, processInstanceId);

        HashMap<String, Object> variables = new HashMap<>();
        variables.put("shiftCondition", "return-N-1");

        String userId = sysUser.getUserCode();
        EiInfo inInfo = new EiInfo();
        inInfo.set("taskId", taskId);
        inInfo.set("userId", userId);
//        inInfo.set("transitionKey","return-N-1");
        inInfo.set("comment", "同意");
        inInfo.set("approvalResult", "同意");
        inInfo.set("nextActivityUserList", nextActivityUserList);
        inInfo.set("variables", variables);
        inInfo.set(EiConstant.serviceName, "EW11");
        inInfo.set(EiConstant.methodName, "submit");
        EiInfo outInfo = XLocalManager.call(inInfo);
        int status = outInfo.getStatus();
        return AjaxResult.success();
    }

    @ApiOperation("回退流程（测试方法）")
    @PostMapping("testBack")
    public AjaxResult testBack(String processInstanceId) {
        XtzyUser sysUser = ShiroUtils.getUser();

        FltdProcessServiceImpl processService = new FltdProcessServiceImpl();
        String taskId = processService.getTaskId(sysUser, processInstanceId);

        String userId = sysUser.getUserCode();

        EiInfo inInfo = new EiInfo();
        List<Map<String, Object>> list = new ArrayList<>();

        //查询要提交的任务id
        Map<String, Object> map = new HashMap<>();
        map.put("taskId", taskId);
        map.put("userId", userId);
        map.put("actvityKey", "A02");
        map.put("comment", "不同意");
        map.put("approvalResult", WorkflowConstant.DISAPPROVAL);
        list.add(map);

        inInfo.set("list", list);
        inInfo.set(EiConstant.serviceName, "EW11");
        inInfo.set(EiConstant.methodName, "batchReturns");
        EiInfo outInfo = XLocalManager.call(inInfo);
        int status = outInfo.getStatus();
        return AjaxResult.success("操作成功", status);
    }

    @ApiOperation("撤回流程-无法使用（测试方法）")
    @PostMapping("testCancel")
    public AjaxResult testCancel(String processInstanceId) {
        XtzyUser sysUser = ShiroUtils.getUser();
        EiInfo inInfo = new EiInfo();

        XtzyUser cancelUser = new XtzyUser();
        cancelUser.setUserCode("cuishihao");
        cancelUser.setUserDesc("Chris Cui");
        FltdProcessServiceImpl processService = new FltdProcessServiceImpl();
        String taskId = processService.getTaskId(cancelUser, processInstanceId);

        List<String> list = new ArrayList<>();
        list.add(taskId);
        inInfo.set("list", list);

        inInfo.set(EiConstant.serviceName, "EW11");
        inInfo.set(EiConstant.methodName, "batchCacelTask");
        EiInfo outInfo = XLocalManager.call(inInfo);
        int status = outInfo.getStatus();
        return AjaxResult.success("操作成功", status);
    }

    @ApiOperation("任务转移（测试方法）")
    @PostMapping("testChange")
    public AjaxResult testChange(String processInstanceId, String assignee) {
        XtzyUser sysUser = ShiroUtils.getUser();

        EiInfo inInfo = new EiInfo();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        String userId = sysUser.getUserCode(); //当前用户
        String comment = "麻烦代为处理"; //附言
        map.put("userId", userId);
        map.put("assignee", assignee);
        map.put("comment", comment);
        map.put("processInstanceId", processInstanceId);
        list.add(map);
        inInfo.set("list", list);
        inInfo.set(EiConstant.serviceName, "EW11");
        inInfo.set(EiConstant.methodName, "batchReassignTasks");
        EiInfo outInfo = XLocalManager.call(inInfo);
        int status = outInfo.getStatus();
        return AjaxResult.success("操作成功", status);
    }

    @ApiOperation("获取节点的回退配置（测试方法）")
    @PostMapping("getReturnTarget")
    public AjaxResult getReturnTarget(String processInstanceId, String activityKey) {
        XtzyUser sysUser = ShiroUtils.getUser();

        XtzyCompany company = companyService.get("BGTAZA00");

        FltdProcessServiceImpl processService = new FltdProcessServiceImpl();
        String taskId = processService.getTaskId(sysUser, processInstanceId);

        EiInfo inInfo = new EiInfo();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("taskId", taskId);
        map.put("activityKey", activityKey);
        list.add(map);
        inInfo.set("list", list);
        inInfo.set(EiConstant.serviceName, "EW11");
        inInfo.set(EiConstant.methodName, "getReturnTargetActivity");
        EiInfo outInfo = XLocalManager.call(inInfo);
        List<Map<String, String>> nodeReturnSetList = (List<Map<String, String>>) outInfo.get("result");
        return AjaxResult.success("操作成功", nodeReturnSetList);
    }


    @ApiOperation("（测试方法）")
    @PostMapping("test")
    public AjaxResult test(String processInstanceId, String activityKey) {
//        XtzyUser sysUser = ShiroUtils.getUser();
        List<String> ids = new ArrayList<>();
//        ids.add(vo.getBusinessKey());
//        List<String> businessKeys = new ArrayList<>();
//        workFlowManager.getgetProcessKeyByBusinessKey(sysUser,businessKeys);
//        workFlowManager.batchDeleteProcessInstances(sysUser,ids);

//        workFlowManager.getInfoListByBusinessKey(sysUser, ids);

        XtzyUser sysUser = new XtzyUser();
        sysUser.setUserCode("lishaoqing");
        String userId = sysUser.getUserCode();

//        EiInfo inInfo  = new EiInfo();
        FltdProcessServiceImpl processService = new FltdProcessServiceImpl();
        String taskId = processService.getTaskId(sysUser, processInstanceId);

        TaskService taskService = ProcessEngines.getDefaultProcessEngine().getTaskService();
        taskService.setAssignee(taskId, "045644");

//        inInfo.set("taskId",taskId);
//        inInfo.set("activityKey",activityKey);
//
//        inInfo.set(EiConstant.serviceName,"EW11");
//        inInfo.set(EiConstant.methodName,"getActivityInfoByProcessKey");
//        EiInfo outInfo = XLocalManager.call(inInfo);
//        List<Map<String, Object>> nodeInfoAndApprover = (List<Map<String, Object>>)outInfo.get("processKey");

//        EiInfo inInfo  = new EiInfo();
//        List<Map<String, Object>> list = new ArrayList<>();
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("taskId",taskId);
//        map.put("userId",userId);
//        map.put("comment", "撤回");
//        map.put("approvalResult", WorkflowConstant.CANCEL);
//        list.add(map);
//
//        inInfo.set("list",list);
//        inInfo.set(EiConstant.serviceName,"EW11");
//        inInfo.set(EiConstant.methodName,"batchReturns");
//        EiInfo outInfo = XLocalManager.call(inInfo);
//        int status = outInfo.getStatus();


//        EiInfo inInfo = new EiInfo();
//        inInfo.set("userId",userId);
//
//        inInfo.set(EiConstant.serviceName,"EW11");
//        inInfo.set(EiConstant.methodName,"getTaskList");
//        EiInfo outInfo = XLocalManager.call(inInfo);
//        int status = outInfo.getStatus();

//        EiInfo inInfo  = new EiInfo();
//        String userCode = "045644";
//        List<String> taskList = new ArrayList<>();
//        taskList.add(taskId);
//        inInfo.set("userId",userCode);
//        inInfo.set("taskList",taskList);
//        inInfo.set(EiConstant.serviceName,"EW11");
//        inInfo.set(EiConstant.methodName,"batchClaimTask");
//        EiInfo outInfo = XLocalManager.call(inInfo);
//        int status = outInfo.getStatus();

        int status = 1;

        return AjaxResult.success("操作成功", status);
    }


}
